package com.smyh.UIM.record;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.smyh.UIM.HostFragment;
import com.smyh.UIM.MainActivity;
import com.smyh.UIM.R;
import com.smyh.cache.UIM.HostFaultRecordUI;
import com.smyh.cache.UIM.MainCahce;
import com.smyh.cache.UIM.right.host.wave_record.FaultRecordCache;
import com.smyh.common.MinaClientThread;
import com.smyh.method.WaveRecordMethod;
import com.smyh.model.host.record.HostFaultRecordModel;
import com.smyh.model.host.record.HostSyncRecordModel;
import com.smyh.protcol.device.CMDUtil;

import org.apache.mina.core.buffer.IoBuffer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * Created by Administrator on 2016/7/27.
 */
public class HostFaultRecordFm extends Fragment{

    /**
     * 主机同步视图组件
     */

    public RadioButton groupNum01,groupNum02,groupNum03,phase01,phase02,phase03,phase04;
    public RadioGroup radioGroup01,radioGroup02;
    public Button contentsBtn,faultElecReadBtn,faultVoltReadBtn;
    public Spinner spinnerContents;
    private LineChartView chartView;
    static Axis axisX;
    static LineChartData data;
    static Line line;
    static  Line line2;
    static List<Line> lines = new ArrayList<>();

    public static int checkContentIndex = 0;

    private ArrayAdapter<String> spinnerAdapter;

    public static Handler handler;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_record_host_fault,container,false);

        initView(view);
        initEvent();

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 0:{
                        //录波数据刷新
                        resetRecordData();
                        break;
                    }
                    case 1:{
                        //目录数据刷新
                        long time0 = HostFaultRecordUI.contentsTimeList.get(0);
                        Date date0 = new Date(time0);
                        long time1 = HostFaultRecordUI.contentsTimeList.get(1);
                        Date date1 = new Date(time1);
                        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss SSS");

                        List<String> spinnerList = new ArrayList<>();
                        spinnerList.add("0: " + sdf.format(date0));
                        spinnerList.add("1: " + sdf.format(date1));
                        spinnerAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item,spinnerList);
                        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                        spinnerContents.setAdapter(spinnerAdapter);
                        break;
                    }
                }
            }
        };
        return view;
    }

    private void initEvent() {
        spinnerContents.setOnItemSelectedListener(itemListener);

        radioGroup01.setOnCheckedChangeListener(checkListener);
        radioGroup02.setOnCheckedChangeListener(checkListener);
        contentsBtn.setOnClickListener(btnClickListener);
        faultElecReadBtn.setOnClickListener(btnClickListener);
        faultVoltReadBtn.setOnClickListener(btnClickListener);
    }

    private void initView(View view){
        groupNum01 = (RadioButton) view.findViewById(R.id.groupNum01);
        groupNum02 = (RadioButton) view.findViewById(R.id.groupNum02);
        groupNum03 = (RadioButton) view.findViewById(R.id.groupNum03);
        phase01 = (RadioButton) view.findViewById(R.id.phase01);
        phase02 = (RadioButton) view.findViewById(R.id.phase02);
        phase03 = (RadioButton) view.findViewById(R.id.phase03);
        phase04 = (RadioButton) view.findViewById(R.id.phase04);

        radioGroup01 = (RadioGroup) view.findViewById(R.id.radioGroup01);
        radioGroup02 = (RadioGroup) view.findViewById(R.id.radioGroup02);

        contentsBtn = (Button) view.findViewById(R.id.contentsBtn);
        faultElecReadBtn = (Button) view.findViewById(R.id.faultElecReadBtn);
        faultVoltReadBtn = (Button) view.findViewById(R.id.faultVoltReadBtn);

        chartView = (LineChartView) view.findViewById(R.id.host_fault_chart);
        chartView.setInteractive(true);
        //设置行为属性，支持缩放、滑动以及平移
        chartView.setInteractive(true);
        chartView.setZoomType(ZoomType.HORIZONTAL);
        chartView.setVisibility(View.VISIBLE);
        // 设置线的颜色为蓝色，曲线光滑，显示标注 是否显示圆点  是否点击坐标提示
        line = new Line().setColor(Color.BLUE).setCubic(true).setHasLabels(false).setHasPoints(true).setHasLabelsOnlyForSelected(true);
        line2 = new Line().setColor(Color.RED).setCubic(true).setHasLabels(false).setHasPoints(true).setHasLabelsOnlyForSelected(true);
        data = new LineChartData();
        data.setValueLabelBackgroundColor(Color.TRANSPARENT);//此处设置坐标点旁边的文字背景
        data.setValueLabelBackgroundEnabled(false);
        data.setValueLabelsTextColor(Color.RED);  //此处设置坐标点旁边的文字颜色

        //坐标轴
        axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);
        axisX.setTextColor(Color.BLUE);
        axisX.setName("采集时间");
        axisX.setMaxLabelChars(10);
        resetRecordData();

        List<String> spinnerList = new ArrayList<>();
        spinnerList.add("0: MM-dd HH:mm:ss SSS");
        spinnerList.add("1: MM-dd HH:mm:ss SSS");
        spinnerAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item,spinnerList);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinnerContents = (Spinner) view.findViewById(R.id.spinnerContents);
        spinnerContents.setAdapter(spinnerAdapter);
    }

    /**
     *
     * @param dataType
     * 0-刷新录波数据
     * 1-刷新目录数据
     */
    public static void freshHostSyncDataModel(int dataType) {
        Message msg = new Message();
        msg.what = dataType;
        handler.sendMessage(msg);
    }

    private AdapterView.OnItemSelectedListener itemListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            checkContentIndex = position;
            FaultRecordCache.setEEIndex(position);
            FaultRecordCache.setEFIndex(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };


    private View.OnClickListener btnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int clickId = v.getId();
            switch (clickId){
                case R.id.contentsBtn:{
                    //下发报文
                    if (HostFragment.connection_btn.isChecked()) {
                        if(MinaClientThread.session != null && MinaClientThread.session.isConnected()){
                            IoBuffer catalogForFault = CMDUtil.getCatalogForFault();
                            MinaClientThread.session.write(catalogForFault);
                        }else {
                            Toast.makeText(getContext(),"通讯已经断开！",Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getContext(),"请连接设备，使数据透传！",Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case R.id.faultElecReadBtn:{
                    //下发报文
                    if (HostFragment.connection_btn.isChecked()) {
                        if(MinaClientThread.session != null && MinaClientThread.session.isConnected()){
//                            IoBuffer catalogForSync = CMDUtil.getCatalogForSync();
//                            MinaClientThread.session.write(catalogForSync);
                            WaveRecordMethod.readEEWave();
                        }else {
                            Toast.makeText(getContext(),"通讯已经断开！",Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getContext(),"请连接设备，使数据透传！",Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case R.id.faultVoltReadBtn:{
                    //下发报文
                    if (HostFragment.connection_btn.isChecked()) {
                        if(MinaClientThread.session != null && MinaClientThread.session.isConnected()){
//                            IoBuffer catalogForSync = CMDUtil.getCatalogForSync();
//                            MinaClientThread.session.write(catalogForSync);
                            WaveRecordMethod.readEFWave();
                        }else {
                            Toast.makeText(getContext(),"通讯已经断开！",Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getContext(),"请连接设备，使数据透传！",Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }
        }
    };

    private RadioGroup.OnCheckedChangeListener checkListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId){
                case R.id.groupNum01:{
                    HostFaultRecordUI.chooseGroup = 1;
                    break;
                }
                case R.id.groupNum02:{
                    HostFaultRecordUI.chooseGroup = 2;
                    break;
                }
                case R.id.groupNum03:{
                    HostFaultRecordUI.chooseGroup = 3;
                    break;
                }
                case R.id.phase01:{
                    HostFaultRecordUI.choosePhase = 1;
                    break;
                }
                case R.id.phase02:{
                    HostFaultRecordUI.choosePhase = 2;
                    break;
                }
                case R.id.phase03:{
                    HostFaultRecordUI.choosePhase = 3;
                    break;
                }
                case R.id.phase04:{
                    HostFaultRecordUI.choosePhase = 4;
                    break;
                }
            }
        }
    };


    private void resetRecordData(){
        List<PointValue> values = new ArrayList<>();
        List<PointValue> values2 = new ArrayList<>();
        List<AxisValue> axisValues = new ArrayList<>();

        List<Integer> hostFaultElecList = null;

        try {
            hostFaultElecList = HostFaultRecordModel.faultElectMapModel.get(MainCahce.chooseDeviceAddr)
                    .get(HostFaultRecordUI.chooseGroup).get(HostFaultRecordUI.choosePhase)
                    .get(HostSyncRecordModel.contentsSyncTimes.get(checkContentIndex));
        }catch (Exception e){

        }

        for (int i = 0; hostFaultElecList!=null && i < hostFaultElecList.size(); i++) {
            values.add(new PointValue(i, hostFaultElecList.get(i)));
            axisValues.add(new AxisValue(i).setLabel(i+""));//为每个对应的i设置相应的label(显示在X轴)
        }
        List<Integer> hostFaultVoltList = null;

        try {
            hostFaultVoltList = HostFaultRecordModel.faultVoltMapModel.get(MainCahce.chooseDeviceAddr)
                    .get(HostFaultRecordUI.chooseGroup).get(HostFaultRecordUI.choosePhase)
                    .get(HostSyncRecordModel.contentsSyncTimes.get(checkContentIndex));
        }catch (Exception e){

        }

        for(int i = 0;hostFaultVoltList!=null&&i<hostFaultVoltList.size();i++){
            values2.add(new PointValue(i, (hostFaultVoltList.get(i))));
        }

        line2.setValues(values2);
        lines.add(line2);
        line.setValues(values);
        lines.add(line);
        data.setLines(lines);
        data.setAxisXBottom(axisX);
        axisX.setValues(axisValues);
        chartView.setLineChartData(data);

        Viewport tempViewport = new Viewport(0, chartView.getMaximumViewport().height(), 40, 0) ;
        chartView.setCurrentViewport(tempViewport);

    }

}
